package com.zbxx.leetcode.str;

public class stringcompress {

    public int compress(char[] chars) {
        if (chars.length < 2) {
            return 1;
        }
        int length = 1;
        int nums = 1;
        int index = 0;
        int setindex = 0;
        int currentindex = 1;
        boolean reapeat = false;
        while (currentindex < chars.length) {
            if (chars[currentindex] == chars[index]) {
                nums++;
                if (!reapeat) {
                    setindex++;
                    reapeat = true;
                }
                currentindex++;
            } else {
                if (nums != 1) {
                    char[] cs = String.valueOf(nums).toCharArray();
                    length += cs.length;
                    System.arraycopy(cs, 0, chars, setindex, cs.length);
                    setindex += cs.length - 1;
                }
                reapeat = false;
                length++;
                index = currentindex;
                chars[++setindex] = chars[currentindex];
                currentindex++;
                nums = 1;
            }
        }
        if (nums != 1) {
            char[] cs = String.valueOf(nums).toCharArray();
            length += cs.length;
            System.arraycopy(cs, 0, chars, setindex, cs.length);
        }
        return length;
    }


/*    public int compress(char[] chars) {
        TreeNode n = new TreeNode(chars[0]);
        TreeNode head = n;
        int length = 0;
        for (int i = 1; i < chars.length; i++) {
            if((int)chars[i]==n.val){
                n.left = n.left==null? new TreeNode(1):n.left;
                n.left.val++;
                continue;
            }
            n.right = new TreeNode(chars[i]);
            n = n.right;
        }
        int index = 0;
        while (head!=null){
            chars[index++] = (char) head.val;
            length++;
            if(head.left!=null){
                char[] chars1 = String.valueOf(head.left.val).toCharArray();
                for (char c : chars1) {
                    length++;
                    chars[index++] = c;
                }
            }
            head = head.right;
        }
        return length;
    }*/

}
